package com.luck.easyfoodbatch.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.PayShopFeeModel;
import com.luck.easyfoodbatch.mvp.mine.PayShopFeePresenter;
import com.luck.easyfoodbatch.mvp.mine.PayShopFeeView;
import com.luck.easyfoodbatch.mvp.model.PayShopFeeM;
import com.luck.easyfoodbatch.pay.PayResult;
import com.luck.easyfoodbatch.simcpux.Constants;
import com.luck.easyfoodbatch.util.AlipayUtil;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PaymentBondActivity extends BaseActivity implements PayShopFeeView {
    @BindView(R.id.rl_zhifubao)
    RelativeLayout rlZhifubao;
    @BindView(R.id.rl_wechat)
    RelativeLayout rl_wechat;
    private PayShopFeeModel shopFeeModel;
    @BindView(R.id.btn_apply)
    Button btn_apply;
    @BindView(R.id.iv_alipy)
    ImageView iv_alipy;
    @BindView(R.id.iv_wechat)
    ImageView iv_wechat;
    @BindView(R.id.tv_money)
    TextView tv_money;
    private IWXAPI api;
    private int pay_type = 1;
    private int type = 0;
    private static final int SDK_PAY_FLAG = 1;
    private Handler MyHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                        user.setIs_shoper(2);
                        App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                        T.showToast(mContext, "支付成功");
                        int is_year_fee = user.getIs_year_fee();//是否交年费 0为未交，1为已交
                        switch (is_year_fee) {
                            case 0:
                                startAct(AnnualFeeActivity.class);
                                break;
                            case 1:
                                break;
                        }
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }

            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("action.app.refresh.pay")) {
                int is_year_fee = user.getIs_year_fee();//是否交年费 0为未交，1为已交
                switch (is_year_fee) {
                    case 0:
                        startAct(AnnualFeeActivity.class);
                        finish();
                        break;
                    case 1:
                        PaymentBondActivity.this.setResult(RESULT_OK);
                        finish();
                        break;
                }

            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_payment_bond, "支付保证金", "说明", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        type = 1;
        shopFeeModel = new PayShopFeePresenter(this, mContext);
        shopFeeModel.requestPayShopFee(pay_type);
        registerReceiver(receiver, "action.app.refresh.pay");
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constants.APP_ID);
    }

    @Override
    public void rightClick() {
        super.rightClick();
        startAct(PaymentBondHttpActivity.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                setResult(RESULT_OK);
                finish();
                return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }

    @Override
    public void payShopFeeSuccess(PayShopFeeM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                // 订单生成成功 支付 1支付宝2微信
                PayShopFeeM.DataBean bean = model.getData();
                if (type == 1) {
                    tv_money.setText(bean.getOrder_price() + "元");
                    type = 0;
                } else {
                    String params = bean.getParams();
                    if (!Tools.isNull(bean.getOrder_price())) {
                        if (!bean.getOrder_price().equals("0")) {
                            switch (pay_type) {
                                case 1:
                                    new AlipayUtil(PaymentBondActivity.this, params, MyHandler);
                                    break;
                                case 2:
                                    wechatApply(bean);
                                    break;
                            }
                        }
                    }
                }
            } else {
                T.showToast(mContext, model.getMsg());
            }
        }
    }

    /**
     * 微信支付
     *
     * @param bean
     */
    private void wechatApply(PayShopFeeM.DataBean bean) {
        try {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = bean.getPackageX();
            req.sign = bean.getSign();
            Toast.makeText(this, "正在发起微信支付，请稍候...", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(Constants.APP_ID);
            api.sendReq(req);
        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @OnClick({R.id.rl_zhifubao, R.id.rl_wechat, R.id.btn_apply})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_zhifubao:
                pay_type = 1;
                type = 0;
                iv_alipy.setImageResource(R.mipmap.select_sel_1x);
                iv_wechat.setImageResource(R.mipmap.select_def_1x);
                break;
            case R.id.rl_wechat:
                pay_type = 2;
                type = 0;
                iv_alipy.setImageResource(R.mipmap.select_def_1x);
                iv_wechat.setImageResource(R.mipmap.select_sel_1x);
                break;
            case R.id.btn_apply:
                //支付方式 1支付宝 2微信
                showProgressDialog(getString(R.string.app_loading));
                shopFeeModel.requestPayShopFee(pay_type);
                break;
        }
    }
}
